<template>
    <div class="pe-collapse-item" :class="[show ? 'pe-collapse-active' : '']">
        <button @click="onClick" :disabled="disabled" class="pe-collapse-item-title">
            <slot name="title">{{ title }}</slot>
        </button>
        <Transition name="collapse">
            <div v-show="show" class="pe-collapse-item-content">
                <slot></slot>
            </div>
        </Transition>
    </div>
</template>

<script setup lang="ts">
import { computed, inject, ref, toRaw } from "vue"

interface Props {
    name?: string | number,
    title?: string,
    disabled?: boolean
}

const props = withDefaults(defineProps<Props>(), {
    title: "",
    disabled: false
})

const activeName = inject("pe-collapse-active", ref<string | number | Array<string | number>>())
const accordionValue = inject("pe-collapse-accordion", ref<boolean>(false))
const onChange = inject("pe-collapse-change", Function, true)

const onClick = () => {
    if (accordionValue.value) {
        let val = activeName.value === props.name ? undefined : props.name
        activeName.value = val
        onChange(val)
    } else {
        if (activeName.value instanceof Array) {
            if (typeof props.name === 'number' || typeof props.name === 'string') {
                let arr = activeName.value
                if (!arr.includes(props.name)) {
                    arr.push(props.name)
                } else {
                    arr = arr.filter(item => item !== props.name)
                }
                activeName.value = arr
                onChange(toRaw(arr))
            }
        } else {
            let arr = []
            if (typeof props.name === 'number' || typeof props.name === 'string') {
                arr.push(props.name)
            }
            activeName.value = arr
            onChange(arr)
        }
    }
}

const show = computed(() => {
    if (activeName.value instanceof Array) {
        if (typeof props.name === 'number' || typeof props.name === 'string') {
            return activeName.value.includes(props.name)
        }
    } else {
        if (typeof props.name === 'number' || typeof props.name === 'string') {
            return activeName.value === props.name
        }
    }
    return false
})
</script>

<script lang="ts">
export default {
    name: "pe-collapse-item"
}
</script>